import React, { useEffect, useState } from "react";
import { Tag, Space } from "antd";
import { useSelector, useDispatch } from "react-redux";
import { useLocation, useNavigate } from "react-router-dom";
import { closeTab } from "../../redux/reducers/tab";
import "./index.css";

const CommonTag = () => {
  // 从redux中获取tabList
  const tabList = useSelector((state) => state.tab.tabList);
  const [currentKey, setCurrentKey] = useState([]);
  const [closeAction, setCloseAction] = useState(null);
  const action = useLocation();
  const dispatch = useDispatch();
  const navigate = useNavigate();

  // 监听路由变化，同步更新高亮
  useEffect(() => {
    setCurrentKey([action.pathname]);
  }, [action.pathname]);

  // 关闭tag
  const handleClose = (tag) => {
    if (tag.name === "home") return; // 首页标签不可关闭

    const isCurrentTab = tag.path === action.pathname

    setCloseAction({
      tag,
      isCurrentTab,
      preCloseIndex: tabList.findIndex(t => t.path === tag.path)
    });

    dispatch(closeTab(tag));
  };

  useEffect(() => {
    if (!closeAction) return
    const { tag, isCurrentTab, preCloseIndex } = closeAction;
    // 关闭的是当前页
    if(isCurrentTab) {
      if(preCloseIndex < tabList.length) {
        navigate(tabList[preCloseIndex].path)
      } else if(preCloseIndex > 0) {
        navigate(tabList[preCloseIndex - 1].path)
      } else {
        navigate("/home")
      }
    } else {
      console.log(`已关闭非当前页：${tag.label}，页面保持不变`)
    }

  }, [tabList, closeAction, navigate]);

  // 点击tag
  const handleChange = (tag) => {
    navigate(tag.path);
  };

  return (
    <Space className="common-tag" size={[0, 8]} wrap>
      {tabList.map((item) => (
        <Tag
          key={item.name}
          color={item.path === currentKey[0] ? "#55acee" : undefined}
          closable={item.name !== "home"}
          onClose={() => handleClose(item)}
          onClick={() => handleChange(item)}
        >
          {item.label}
        </Tag>
      ))}
    </Space>
  );
};

export default CommonTag;
